import {getWy} from '@/uni_modules/wy-core/context'
var wy=getWy()
let lifeData = uni.getStorageSync('lifeData') || {};
let $user = lifeData.$user || {};
lifeData.core=lifeData.core||{}
const state={
	userInfo:$user.userInfo||{
		uid:0, //用户编号
		_id:'',
		avatar:'',//头像
		nickname:'',//昵称
		username:'',//用户名
		mobile:'', //手机号
		desc:'',   //介绍
        extra:{},//其它属性
		permission:[]  ,//权限值
		role:[]  //角色组
	},
	userAccount:{  //账户信息
		experience:'',
		balance:0, //收入 用户余额转入
		fans:'',
		follow:'',
		gold:0,  //代金券 赠送
		income:0,//收入 用户直接充值
		money:0 //余额 充值
	},
	theme:lifeData.core.theme||'blue',
	themeClass:lifeData.core.themeClass||{
		head:{}
	},
	themeColor:lifeData.core.themeColor||{},
	localAccount:lifeData.core.localAccount||{},
	token:lifeData.core.token||'',
	taskList:[],
	taskStart:false,
	dictStore:lifeData.core.dictStore ||{},  //字典
	hooks:{},
	publishs:{},
	subscribes:{},
	version:lifeData.core.version || {} //系统版本

};
const getters={
	DictStore:(state)=>{
		let {Dict}= wy.config
		var obj=wy.pubfn.deepMerge(Dict,state.dictStore)
		return obj
	},
	Version:(state)=>{
		return state.version
	},
	Hooks:(state)=>{
		let {Hooks}= wy.config
		var obj=wy.pubfn.deepMerge(Hooks,state.hooks)
		return obj
	},
	UID:(state)=>{
		let model=wy.vk.getVuex('$user.userInfo') || {}
		let user={
			...state.userInfo,
			...model
		}
		let {uid,_id}=user
		return uid || _id
	},
	IsLogin:(getters)=>{
		let model=wy.vk.getVuex('$user.userInfo') || {}
		let user={
			...state.userInfo,
			...model
		}
		let {uid,_id}=user
		if(uid || _id){
			return true
		}
		else{
			return false
		}
	},
	UserInfo: (state) => {
		let model=wy.vk.getVuex('$user.userInfo') || {}
		let user={
			...state.userInfo,
			...model
		}
		let {nickname,username,avatar,uid,_id}=user
		if(!nickname){
			user.nickname=username
		}
		if(!avatar){
			user.avatar=wy.localUrl('logo') //wy.config.Local.imgs.logo
		}
		if(!uid){
			user.uid=_id
		}
		return user
	},
	UserAccount:state=>{

		return {
			experience:0,
			balance:0,
			fans:0,
			follow:0,
			gold:0,
			income:0,
			money:0 ,
			...state.userAccount
		}
	},
	//本地账户
	LocalAccount: (state) => {
		let userModel=wy.vk.getVuex('$user.userInfo') || {}

		var localAccount=wy.vk.getVuex('core.localAccount') || {}
		let locals={}
		if(userModel&&userModel.hasOwnProperty('_id')){
			Object.assign(localAccount,{[userModel._id]:userModel})
		}
		for(let key in localAccount){
			var model={
				...state.userInfo,
				...localAccount[key]
			}
			let {_id}=model
			Object.assign(locals,{[_id]:model})
		}
		return locals
	}
};
const mutations={
	setVersion:(state,model)=>{
		state.version=Object.assign(state.version,model)
		wy.vk.setVuex('core.version',state.version)
	},
	pushTask:(state,model)=>{
		state.taskList.push(model)
	},
	setUserAccount:(state,model)=>{
		state.userAccount=model
		//console.log(state.userAccount)
	},
	resetUser:(state,data)=>{
		wy.callFunctionUtil.deleteToken ()
		state.userAccount={}
	},
	setHooks:(state,model)=>{
		state.hooks=model
	},
	resetDictStore:(state,model)=>{
		state.dictStore=model
		wy.vk.setVuex('core.dictStore',state.dictStore)
	},
	setDictStore:(state,model)=>{
		state.dictStore=Object.assign(state.dictStore,model)
		wy.vk.setVuex('core.dictStore',state.dictStore)
	},
	publish:(state,model)=>{
		let {name,data}=model
		state.publishs=Object.assign(state.publishs,{[name]:model})
		//自动触发
		if(state.subscribes.hasOwnProperty(name)){
			const list=state.subscribes[name]
			for(let i=0;i<list.length;i++){
				let {param,fn,name,uuid}=list[i]
				let {auto,onece}=param
				if(auto && wy.pubfn.isFunction(fn)){
					fn({param,name,uuid,data})
				}
			}

		}
		wy.log(state.publishs)

	},
	unpushlish:(state,model)=>{
		let {name}=model
		if(state.publishs.hasOwnProperty(name)){
			delete state.publishs[name]
		}
	},
	subscribe:(state,model)=>{
		let {name,param}=model   //,fn,param,uuid
		model.param={
			auto:false, //自动触发
			...param
		}
		if(state.subscribes.hasOwnProperty(name)){
			let {uuid}=model
			if(uuid){
				var index=state.subscribes[name].findIndex((e)=>{
					return e.uuid && e.uuid === uuid
				})
				if(index>=0){
					return
				}
			}
			state.subscribes[name].push(model)
		}
		else{
			state.subscribes=Object.assign(state.subscribes,{[name]:[model]})
		}
		wy.log(state.subscribes)
	},
	doemit:(state,model)=>{
		let {name,uuid,onece,clear}=model
		if(uuid && state.publishs.hasOwnProperty(name)){
			let {data}=state.publishs[name]
			const copys=state.subscribes
			for(let key in copys){
				let list=copys[key]
				var index=list.findIndex((e)=>{
					return e.uuid === uuid
				})
				if(index>=0){
					let {param,fn}=list[index]
					if(wy.pubfn.isFunction(fn)){
						if(onece){
							state.subscribes[key].splice(index,1)
						}
						fn({param,name,data,uuid})
					}
					break
				}
			}
			//是否删除发布
			if(clear){
				delete state.publishs[name]
			}


		}
	},
	unsubscribe:(state,model)=>{
		let {name,uuid,clear}=model
		if(name && state.subscribes.hasOwnProperty(name)){
			delete state.subscribes[name]
		}
		if(name&&clear && state.publishs.hasOwnProperty(name)){
			delete state.publishs[name]
		}
		if(uuid){
			const copys=state.subscribes
			for(let key in copys){
				let list=copys[key]
				var index=list.findIndex((e)=>{
					return e.uuid === uuid
				})
				if(index>=0){
					state.subscribes[key].splice(index,1)
					break
				}
			}
		}
		wy.log(state.subscribes)
	}
};
const actions={
    setUserLoginOut({commit}){
        console.debug('-----setUserLoginOut')
        commit('resetUser',{})
        commit('resetDictStore',{})
    },
    //外部登陆对接
    setUserLogin({commit},data){
        let {token,userInfo}=data
        //uid:0,
      //  _id:'',
      //  avatar:'',
      //  nickname:'',
      //  username:'',
       // mobile:'',

        if(token && token.token){
            wy.callFunctionUtil.saveToken(token)
        }
        if(userInfo){
            wy.callFunctionUtil.updateUserInfo({userInfo})
        }
    },

	setVersion({commit,state},option={}){
		commit('setVersion',option)
	},
	/**
	 *
	 * @param {*} 新增设置字典
	 */
	setDictStore({commit,state},option={}){
		commit('setDictStore',option)
	},
	resetDictStore({commit},option={}){
		commit('resetDictStore',option)
	},
	/**
	 *
	 * @param {*} keys 需加载的字典key集合
	 * @param {*} func 获取字典值的方法
	 * @param {*} prekeys 需要预加载的字典key集合
	 */
	async loadDictStore({commit,getters,dispatch},option={}){
		 let {expired,dictFun}=wy.config.Local.dictStore
		 let {keys,func,prekeys,ispreload,success}=option
		 if(expired){
			  var cacheTime=wy.pubfn.cache.S({
					key:'dictStore.expired'
				})
				if(!cacheTime){
					commit('resetDictStore',{})
					wy.pubfn.cache.S({
						key:'dictStore.expired',
						data:1,
						time:expired
					})
				}
		 }
			const obj=getters.DictStore //{key:value} 
			let result={}
			let noKeys=[]
			keys.forEach((key)=>{
				if(obj.hasOwnProperty(key)){
					result=Object.assign(result,{[key]:obj[key]})
				}
				else{
					noKeys.push(key)
				}
			})
			if(noKeys.length>0 ){
				var newReuslt={}
				if(func){
					newReuslt=await func(noKeys)
				}
				else if(dictFun){
					newReuslt=await wy.dispatch(dictFun,noKeys)
				}
			  commit('setDictStore',newReuslt)
				result=Object.assign(result,newReuslt)
			}
			if(prekeys&&prekeys.length>0){
				setTimeout(()=>{
					dispatch('loadDictStore',{
						keys:prekeys,func,prekeys:null,ispreload:true
					})
				},500)
			}
			console.debug((ispreload?'预':'已')+'加载字典:',result)
			return new Promise((resolve, reject)=>{
				if(success){
					success(result)
				}
				resolve(result)
			})
	},


	/**
	 * 发布 用于异步跨页面通讯
	 * @param {String} name 唯一标识
	 * @param {Object} data 附加数据
	 */
	publish({commit},option={}){
		option={
			name:'',
			data:{},
			...option
		}
		commit('publish',option)
	},
	/**
	 * 订阅 用于异步跨页面通讯
	 * @param {String} name 订阅标识
	 * @param {Function} fn 回调方法
	 * @param {Object} param auto 自动触发
	 * @param {String} uuid 唯一编号，用于取消订阅
	 */
	subscribe({commit},option={}){
		//name,fn,uuid='',param={}
		option={
			name:'',
			fn:null,
			uuid:'',
			param:{},
			...option
		}
		commit('subscribe',option)
	},
	/**
	 * 取消订阅 用于跨页面通讯
	 * @param {Object} param name或者uuid
	 */
	unsubscribe({commit},param){
		commit('unsubscribe',param)
	},
	/**
	 * 触发事件需订阅的时候设置uuid
	 * @param {String} name 订阅标识
	 * @param {String} uuid 唯一标识
	 * @param {Object} data  传入参数
	 */
	doemit({commit},option={}){
		option={
			name:'',
			uuid:'',
			onece:true,
			clear:false,
			...option
		}
		commit('doemit',option)
	},
	StartTask({commit,state},isStart=true){


	},
	PushTask({commit,state},taskFun){
		commit('pushTask',taskFun)
		if(state.taskStart){

		}
	},
	async LoginOut({commit,state},data,option={}){
		let userModel=wy.vk.getVuex('$user.userInfo') || {}
		var sid=wy.getToken()
		if(data){
			data={
				...data,
				sid
			}
		}else{
				data={
					sid
				}
			}
		return new Promise((resolve, reject)=>{
			wy.userCenter.logout({data}).then((res)=>{
				commit('resetUser',res)
				commit('resetDictStore',{})
				resolve(res)
			}).catch((err)=>{
				commit('resetUser',{})
				commit('resetDictStore',{})
				reject(err)
			})
		})

	},
	async checkUserSession({commit},data,option={}){
		return new Promise((resolve, reject)=>{
			wy.callFunction({
				url:'user/pub/userSession',
				data:{},
				success(res) {
					resolve(res.data)
				},fail() {
					commit('resetUser',{})
				}
			})

		})

	},
	async getUserAccount({commit},data,option={}){
		return new Promise((resolve, reject)=>{
			wy.callFunction({
				url:'user/kh/userAccount',
				success(res) {
					if(res.data){
						commit('setUserAccount',res.data)
					}
					resolve(res.data)
				}
			})

		})

	},
	//加载应用配置
	async loadAppConfig({commit},data,option={}){
		return new Promise((resolve, reject)=>{
			wy.callFunction({
				noAlert:true,
				url:'appConfig',
				success(res) {
					if(res.data){
						let {hooks,dictStore,config}=res.data
						if(hooks){
							commit('setHooks',hooks)
						}
						if(dictStore){
							commit('setDictStore',dictStore)
						}
						if(config){
							wy.setLocalConfig(config)
						}
					}
					resolve(res.data)
				}
			})
		})
	}
};
export default {
  namespaced: true,
  state,
  getters,
  actions,
  mutations
}
